#include <WString.h>

#include "WProgram.h"
void setup();
void loop();
int potPin = 0;    
int ledPin = 13;   
int val = 0;       
int val2 =0;
int val3 =0;
int get;
char getArr[10];
int index=0;
String s;
char in;
char c;
int getint;
boolean stateA = false;
boolean stateB = false;
boolean state = false;
int x=0;
int y=0;
int z=0;
int ir=0;
int PWMMotor = 9;

void setup() {
  pinMode(ledPin, OUTPUT);  // declare the ledPin as an OUTPUT
   Serial.begin(9600);      
}

void loop() {
  val = analogRead(0);    // read the value from the sens
  val2 = analogRead(1);
  val3 = analogRead(2);
  ir = analogRead(3);
  x = analogRead(4);
  y = analogRead(5);
  z = analogRead(6);
  
  digitalWrite(ledPin, HIGH);  

  if(Serial.available() > 0){
   // in = Serial.read();
    
    if(index <10){
      in = Serial.read();
      
      int ascii = in;
      //Serial.println(ascii);
      
      if(stateA){
        if(ascii != 76){  // L
         if(index <3){  
          getArr[index] = in;
          index +=1;
         }else{
           index =0;
         }
        }else{
         stateA = !stateA;
         state = !state; 
         //index =0;
        }
      }
      
      if(ascii == 82){  //scanning R
        getArr[index] = in;
        index+=1;
        stateA = !stateA;
      }
       
    }else{
      index = 0;
    }   
   
  }else{
    //detect 
   if(state){ 
     Serial.println("====msg=====");
     for(int i=0;i<index;i++){
       Serial.print("[");
       Serial.print(getArr[i]);
       Serial.print("],");
       
     }
     Serial.println(" ");
     get = (int)getArr[2];
     index = 0;
     state = !state; 
   } 
  }
    
   
 if(get <= 254 && get > 0){
      
   Serial.print("R:");   
   Serial.println(get); 
   analogWrite(PWMMotor,get*2);
   delay(500);
  // index = 0;
   //delay(500);
   //get = 0;
   
  }
 
  Serial.print("d:");
  Serial.print(val);
  Serial.print(",e:");
  Serial.print(val2);  
  Serial.print(",f:");
  Serial.print(val3);
  Serial.print(",x1:");
  Serial.print(x);
  Serial.print(",y1:");
  Serial.print(y);
  Serial.print(",z1:");
  Serial.print(z);
  Serial.print(",ir1:");
  Serial.println(ir);
  //Serial.print(",R:");
  //Serial.println(get);
  
  
  delay(100);
  //analogWrite(3,0);
  digitalWrite(ledPin, LOW);  
}

int main(void)
{
	init();

	setup();
    
	for (;;)
		loop();
        
	return 0;
}

